//
// Created by irvy on 8/6/15.
//

#ifndef MODBUSSERVER_MODBUSSERVER_H
#define MODBUSSERVER_MODBUSSERVER_H

#include <stdlib.h>
#include <iostream>
#include <string>
#include <iostream>
#include <unistd.h>
#include <mutex>
#include "../jsonconfig/jsonconfig.h"
#include "../libmodbus/modbus.h"
#include "../libmodbus/modbus-private.h"
#include "../rtubuffer/rtubuffer.h"

class modbusServer
{

public:
    modbusServer(BridgeConfig *cfg);
    ~modbusServer();
    void exec();

private:
    void log(std::string msg, int level)
    {
        if (!debuglog)
            return;
        if (level == 0 && level >= loglevel)
            std::cout << "\033[36m[modbusserver]\033[0m" << msg << std::endl;
        else if (level == 1 && level >= loglevel)
            std::cout << "\033[36m[modbusserver]\033[0m"
                 << "\033[36m" << msg << "\033[0m" << std::endl;
        else if (level >= 2)
            std::cout << "\033[36m[modbusserver]\033[0m"
                 << "\033[31m" << msg << "\033[0m" << std::endl;
    }
    bool debuglog;
    int loglevel;
    modbus_t *tcp_handler;
    modbus_mapping_t *mapping;
    fd_set refset;
    fd_set rdset;
    int modbussocket;
    uint16_t data[125];
    int fdmax;
    void makeresponse(uint8_t *response, uint8_t *req, uint16_t *data,uint16_t datalen);
};

/**
 * @brief RTU反馈TCP信息格式
 * 
 */
struct ResponseDataType
{
    uint16_t* response_data;    /*<reserved*/
    bool enable;                /*<是否有效*/
    bool miss;                  /*<RTU查询是否Timeout*/
};
/**
 * @brief TCP请求RTU信息格式
 * 
 */
struct RequestDataType
{
    RequestCode cmd;    /*<高优先级指令，来自TCP透传*/
    uint16_t req_data[125]; /*<数据段，批量写入时使用*/
    bool enable;        /*<是否有效*/
};
#endif //MODBUSSERVER_MODBUSSERVER_H